package com.xing.okhttp;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.Arrays;

public class SSLHelper {

    public static SSLContext createSSLContext(boolean usePrivateSSL, boolean useSSL, X509TrustManager x509TrustManager) throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        if ((usePrivateSSL) && (useSSL)) {
            sslContext.init(null, new TrustManager[] { x509TrustManager }, null);
        }
        return sslContext;
    }

    public static X509TrustManager trustManager() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore());
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:"
                    + Arrays.toString(trustManagers));
        }
        return (X509TrustManager) trustManagers[0];
    }


    public static KeyStore keyStore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());

        InputStream in = HttpClientManager.class.getResourceAsStream("/tingyun");
        if (null == in) {
        } else {
            try {
                keystore.load(in, null);
            } finally {
                in.close();
            }
        }
        return keystore;
    }



}
